/*
 * 创建日期 2010-3-1
 */
package com.icss.ah.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.http.HttpMethod;


public class HttpUtil {
	public static final String V1_1 = "1.1";
	public static final String V1_0 = "1.0";

	private String strServer;

	private int port = 80;

	private String out_charset = "gb2312";

	private String strUrl = "/";

	private String strParam = "";

	private Map params = new HashMap();

	private int timeout = -1;

	private String httpver = "1.0";

	public HttpUtil(String strServer) {
		super();
		this.strServer = strServer;
	}
	
	public static JSONObject connectHttp(String url1,String xml,String Character) throws IOException{
		System.out.println(xml);
		JSONObject jsonObject = new JSONObject();
		StringBuffer result = new StringBuffer("");
		
		HttpURLConnection httpURLConnection ;
		URL url;
		try{
			url = new URL(url1);
			httpURLConnection = (HttpURLConnection)url.openConnection();
			
			//加入数据
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Content-Type","application/octet-stream");
			httpURLConnection.setRequestProperty("Content-length", xml.getBytes("utf-8").length+"");
			httpURLConnection.setRequestProperty("pure-data", "yes");
			httpURLConnection.setRequestProperty("Connection","Keep-Alive"); 
			httpURLConnection.setConnectTimeout(6000);
			httpURLConnection.setReadTimeout(6000);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			
			httpURLConnection.connect();
			
			//建立输出流并写入数据
			DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
			outputStream.write(xml.getBytes("utf-8"));
			outputStream.flush();
			outputStream.close();
			
			String aLine = "";
			InputStream is = httpURLConnection.getInputStream();
			InputStreamReader inReader = new InputStreamReader(is,Character);
			
			BufferedReader aReader = new BufferedReader(inReader);
			
			while ((aLine = aReader.readLine()) != null) {
				result.append(aLine).append("\n");
			}
			
			inReader.close();
			aReader.close();
			httpURLConnection.disconnect();
//			System.out.println("===========result:"+result.toString());
			jsonObject = JSONObject.fromObject(result.toString());  
		} catch (Exception e) {
			e.printStackTrace();
			String jsonStr = "{'errorcode':'9999','errornode':'"+e.getMessage()+"'}";
			jsonObject = JSONObject.fromObject(jsonStr);  
		}
		return jsonObject;
		
	}
	public static String connectHttpImg(String url1,InputStream inStream,String Character) throws IOException{
		StringBuffer result = new StringBuffer("");
		
		HttpURLConnection httpURLConnection ;
		URL url;
		try{
			url = new URL(url1);
			httpURLConnection = (HttpURLConnection)url.openConnection();
			
			//加入数据
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Content-Type","application/octet-stream");
			httpURLConnection.setRequestProperty("Content-length",inputByte(inStream).length+"");
			httpURLConnection.setRequestProperty("pure-data", "yes");
			httpURLConnection.setRequestProperty("Connection","Keep-Alive"); 
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setReadTimeout(30000);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			
			httpURLConnection.connect();
			
			//建立输出流并写入数据
			DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
			outputStream.write(inputByte(inStream));
			outputStream.flush();
			outputStream.close();
			
			String aLine = "";
			InputStream is = httpURLConnection.getInputStream();
			InputStreamReader inReader = new InputStreamReader(is,Character);
			
			BufferedReader aReader = new BufferedReader(inReader);
			
			while ((aLine = aReader.readLine()) != null) {
				result.append(aLine).append("\n");
			}
			
			inReader.close();
			aReader.close();
			httpURLConnection.disconnect();
			System.out.println("===========result:"+result.toString());
		} catch (Exception e) {
			e.printStackTrace();
			String jsonStr = e.getMessage();
		}
		return result.toString();
		
	}
	
	public static final byte[] inputByte(InputStream inStream)  
	    throws IOException {  
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
		byte[] buff = new byte[100];  
		int rc = 0;  
		while ((rc = inStream.read(buff, 0, 100)) > 0) {  
		    swapStream.write(buff, 0, rc);  
		}  
		byte[] in2b = swapStream.toByteArray();  
		return in2b;  
	}  

	public static JSONObject GetRequest(String url) throws IllegalStateException, IOException {  
	     JSONObject json = new JSONObject();
		 HttpClient client = new HttpClient();  
	     StringBuilder sb = new StringBuilder();  
	     InputStream ins = null;  
	     // Create a method instance.  
	     GetMethod method = new GetMethod(url);  
	     // Provide custom retry handler is necessary  
	     method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
	          new DefaultHttpMethodRetryHandler(3, false));  
	     try {
	    	 // Execute the method.  
	    	 int statusCode = client.executeMethod(method);  
	         if (statusCode == HttpStatus.SC_OK) {
	             ins = method.getResponseBodyAsStream();  
	             byte[] b = new byte[1024];  
	             int r_len = 0;  
	             while ((r_len = ins.read(b)) > 0) {
	                 sb.append(new String(b, 0, r_len, method.getResponseCharSet()));  
	             }  
	             json = JSONObject.fromObject(sb.toString());
	         } else {  
	             System.err.println("Response Code: " + statusCode);  
	         }  
	     } catch (HttpException e) {  
	         System.err.println("Fatal protocol violation: " + e.getMessage());  
	     } catch (IOException e) {  
	         System.err.println("Fatal transport error: " + e.getMessage());  
	     } finally {  
	         method.releaseConnection();  
	         if (ins != null) { 
	        	 ins.close();  
	         }  
	     }  
	  return json;
	}  
	
	public String getOutCharset() {
		return out_charset;
	}

	public void setOutCharset(String charset) {
		this.out_charset = charset;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getParam() {
		return strParam;
	}

	public String getServer() {
		return strServer;
	}

	public void setServer(String strServer) {
		this.strServer = strServer;
	}

	public String getUrl() {
		return strUrl;
	}

	public void setUrl(String strUrl) {
		this.strUrl = strUrl;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public int getTimeout() {
		return timeout;
	}

	public String getHttpver() {
		return httpver;
	}

	public void setHttpver(String httpver) {
		this.httpver = httpver;
	}

	public void addParam(String key, String value){
		params.put(key, value);
	}

	public void setParams(Map params){
		this.params = params;
	}
	public static String getIpAddr(HttpServletRequest request) {
		String sip = request.getHeader("x-forwarded-for");
		if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {
			sip = request.getHeader("Proxy-Client-IP");
		}
		if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {
			sip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {
			sip = request.getRemoteAddr();
		}
		return sip;
	}

	
	
	public static String createHtml(String action, Map<String, String> hiddens) {
		StringBuffer sf = new StringBuffer();
		sf.append("<form id = \"sform\" action=\"" + action + "\" method=\"post\">");
		if (null != hiddens && 0 != hiddens.size()) {
			Set<Entry<String, String>> set = hiddens.entrySet();
			Iterator<Entry<String, String>> it = set.iterator();
			while (it.hasNext()) {
				Entry<String, String> ey = it.next();
				String key = ey.getKey();
				String value = ey.getValue();
				value = value.replaceAll("\"", "'");
				sf.append("<input type=\"hidden\" name=\"" + key + "\" id=\"" + key + "\" value=\""
						+ value + "\"/>");
			}
		}
		sf.append("</form>");
		sf.append("</body>");
		sf.append("<script type=\"text/javascript\">");
		sf.append("document.all.sform.submit();");
		sf.append("</script>");
		System.out.println(sf.toString());
		return sf.toString();
	}
	
//	private void createStrParam(){
//		Iterator it = params.keySet().iterator();
//		while(it.hasNext()){
//			String key = (String)it.next();
//			String value = URLEncoder.encode((String)params.get(key));
//			strParam += key + "=" + value + "&";
//		}
//		if(strParam.length() != 0){
//			strParam = strParam.substring(0, strParam.length() -1);
//		}
//	}
	
	public static String connectPostHttp(String path,String post){
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            printWriter.write(post);//post的参数 xx=xx&yy=yy
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while((len=bis.read(arr))!= -1){
                bos.write(arr,0,len);
                bos.flush();
            }
            bos.close();
            return bos.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	public static void main(String[] args) {
		String unitUrl = "http://122.112.248.243/icssRetailManage/productData/getProductInfo.do";
		String para = "json={'productId':'','productName':'德芙','unit':''}";
		String str = HttpUtil.connectPostHttp(unitUrl, para);
		System.out.println(unitUrl+"resultJson==="+str.toString());
	}
}